package com.example.smart_city_0829.mainFragment;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.smart_city_0829.R;
import com.example.smart_city_0829.activity.SearchNewsResultActivity;
import com.example.smart_city_0829.base.BaseFragment;
import com.example.smart_city_0829.base.CommonAdapter;
import com.example.smart_city_0829.entity.banner.HomeBannerList;
import com.example.smart_city_0829.entity.news.NewsList;
import com.example.smart_city_0829.entity.news.NewsType;
import com.example.smart_city_0829.entity.server.ServerList;
import com.example.smart_city_0829.retrofit.NetCallBack;
import com.example.smart_city_0829.utils.Constant;
import com.google.android.material.tabs.TabLayout;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import retrofit2.Call;
import retrofit2.Response;

public class MainFragment extends BaseFragment {

    private EditText searchEt;
    private Banner banner;
    private GridView serverGrid;
    private TabLayout newsTypeTab;
    private ListView newsList;

    private List<NewsType.DataBean> newsTypeBean;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    protected void initView() {
        searchEt = (EditText) rootView.findViewById(R.id.search_et);
        banner = (Banner) rootView.findViewById(R.id.banner);
        serverGrid = (GridView) rootView.findViewById(R.id.server_grid);
        newsTypeTab = (TabLayout) rootView.findViewById(R.id.news_type_tab);
        newsList = (ListView) rootView.findViewById(R.id.news_list);

    }

    @Override
    protected void initData() {
        //轮播数据
        api.getHomeBanner().enqueue(new NetCallBack<HomeBannerList>() {
            @Override
            public void onResponse(Call<HomeBannerList> call, Response<HomeBannerList> response) {
                banner.setImages(response.body().getRows().stream().map((item) -> Constant.BASE_URL + item.getAdvImg()).collect(Collectors.toList()));
                banner.start();
                banner.startAutoPlay();
            }
        });
        //全部服务数据
        api.getServerList().enqueue(new NetCallBack<ServerList>() {
            @Override
            public void onResponse(Call<ServerList> call, Response<ServerList> response) {
                final List<ServerList.RowsBean> rows = response.body().getRows();
                final List<ServerList.RowsBean> isShowPartList = rows.subList(0, 9);
                final ServerList.RowsBean moreServer = new ServerList.RowsBean();
                moreServer.setServiceName("更多服务");
                isShowPartList.add(moreServer);
                serverGrid.setAdapter(new ServerGvAdapter(isShowPartList, getContext()));
            }
        });
        //获取新闻分类
        api.getNewsType().enqueue(new NetCallBack<NewsType>() {
            @Override
            public void onResponse(Call<NewsType> call, Response<NewsType> response) {
                newsTypeBean = response.body().getData();
                for (NewsType.DataBean dataBean : newsTypeBean) {
                    final TabLayout.Tab tab = newsTypeTab.newTab();
                    tab.setText(dataBean.getName());
                    tab.setTag(dataBean.getId());
                    newsTypeTab.addTab(tab);
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                final String searchKey = v.getText().toString();
                if (TextUtils.isEmpty(searchKey)) return false;
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    v.setText("");
                    final Intent intent = new Intent(getContext(), SearchNewsResultActivity.class);
                    intent.putExtra("key", searchKey);
                    startActivity(intent);
                }
                return true;
            }
        });
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object o, ImageView imageView) {
                Glide.with(context)
                        .load(o)
                        .into(imageView);
            }
        });
        newsTypeTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                final int tag = (int) tab.getTag();
                final HashMap<String, Object> params = new HashMap<>();
                params.put("type", tag);
                getNewsList(params);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                //ignore
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //ignore
            }
        });
    }

    /**
     * 获取新闻列表
     */
    private void getNewsList(Map<String, Object> params) {
        api.getNews(params).enqueue(new NetCallBack<NewsList>() {
            @Override
            public void onResponse(Call<NewsList> call, Response<NewsList> response) {
                final List<NewsList.RowsBean> data = response.body().getRows();
                newsList.setAdapter(new NewsListAdapter(data, getContext()));
            }
        });
    }


    private static class ServerGvAdapter extends CommonAdapter<ServerList.RowsBean, ServerViewHolder> {

        public ServerGvAdapter(List<ServerList.RowsBean> data, Context context) {
            super(data, context);
        }

        @Override
        protected void setData(ServerList.RowsBean data, int position, ServerViewHolder viewHolder, View convertView, Context context) {
            if (position == 9) {
                Glide.with(context)
                        .load(R.drawable.ic_baseline_more_horiz_24)
                        .into(viewHolder.im);
            } else {
                Glide.with(context)
                        .load(Constant.BASE_URL + data.getImgUrl())
                        .into(viewHolder.im);
            }
            viewHolder.serverName.setText(String.valueOf(data.getServiceName()));
        }



        @Override
        protected ServerViewHolder getViewHolder() {
            return new ServerViewHolder();
        }

        @Override
        protected void initView(ServerViewHolder viewHolder, View convertView) {
            viewHolder.im = (ImageView) convertView.findViewById(R.id.im);
            viewHolder.serverName = (TextView) convertView.findViewById(R.id.server_name);
        }

        @Override
        protected int getItemLayoutResourceId() {
            return R.layout.server_list_item;
        }
    }

    public static class NewsListAdapter extends CommonAdapter<NewsList.RowsBean, NewsListViewHolder> {

        public NewsListAdapter(List<NewsList.RowsBean> data, Context context) {
            super(data, context);
        }

        @Override
        protected void setData(NewsList.RowsBean data, int position, NewsListViewHolder viewHolder, View convertView, Context context) {
            Glide.with(context)
                    .load(Constant.BASE_URL + data.getCover())
                    .into(viewHolder.im);
            viewHolder.im.setVisibility(View.VISIBLE);
            viewHolder.title.setText(String.valueOf(data.getTitle()));
            viewHolder.content.setText(Html.fromHtml(data.getContent()));
            viewHolder.tag1.setText(String.valueOf("评论总数:" + data.getCommentNum()));
            viewHolder.tag3.setText(String.valueOf("发布日期：" + data.getPublishDate()));
        }


        @Override
        protected NewsListViewHolder getViewHolder() {
            return new NewsListViewHolder();
        }

        @Override
        protected void initView(NewsListViewHolder viewHolder, View convertView) {
            viewHolder.im = (ImageView) convertView.findViewById(R.id.im);
            viewHolder.title = (TextView) convertView.findViewById(R.id.title);
            viewHolder.content = (TextView) convertView.findViewById(R.id.content);
            viewHolder.tag1 = (TextView) convertView.findViewById(R.id.tag1);
            viewHolder.tag2 = (TextView) convertView.findViewById(R.id.tag2);
            viewHolder.tag3 = (TextView) convertView.findViewById(R.id.tag3);
        }
    }

    private static class ServerViewHolder {
        ImageView im;
        TextView serverName;
    }

    public static class NewsListViewHolder {
        ImageView im;
        TextView title;
        TextView content;
        TextView tag1;
        TextView tag2;
        TextView tag3;
    }
}
